<script setup lang="ts">
// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 模块导入 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

import { computed, reactive, watch } from 'vue';
import dayjs from 'dayjs';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { fetchAddCjProject, fetchUpdateCjProject } from '@/service/api';
import { useDict } from '@/hooks/business/dict';
import { ObjUtil } from '@/utils/z';

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组件名称 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

defineOptions({
  name: 'CjProjectOperateDrawer'
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组合式函数 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const { formRef, validate, restoreValidation } = useNaiveForm();

const { defaultRequiredRule } = useFormRules();

const { dictOptions } = useDict();

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 父子传参 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

export type OperateType = NaiveUI.TableOperateType | 'view';

interface Props {
  operateType: OperateType;
  rowData?: Api.Sampling.Project | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const isAdd = computed(() => props.operateType === 'add');

// const isEdit = computed(() => props.operateType === 'edit');

// const isView = computed(() => props.operateType === 'view');

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('common.add'),
    edit: $t('common.edit'),
    view: $t('common.view')
  };
  return titles[props.operateType];
});

type Model = Api.Sampling.Project;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: '',
    createUser: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
    code: '',
    name: '',
    projectType: '',
    projectMode: '',
    description: '',
    startDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    endDate: dayjs().format('YYYY-MM-DD HH:mm:ss')
  };
}

type RuleKey = Extract<keyof Api.Sampling.ProjectEdit, 'name' | 'code' | 'projectType' | 'projectMode' | 'startDate' | 'endDate'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  code: defaultRequiredRule,
  projectType: defaultRequiredRule,
  projectMode: defaultRequiredRule,
  startDate: defaultRequiredRule,
  endDate: defaultRequiredRule
};

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

function handleInitModel() {
  Object.assign(model, createDefaultModel());
  if (props.operateType === 'edit' && props.rowData) {
    ObjUtil.assignIgnoring(model, props.rowData, ['createTime', 'startDate', 'endDate']);
    model.createTime = dayjs(props.rowData.createTime).format('YYYY-MM-DD HH:mm:ss');
    model.startDate = dayjs(props.rowData.startDate).format('YYYY-MM-DD HH:mm:ss');
    model.endDate = dayjs(props.rowData.endDate).format('YYYY-MM-DD HH:mm:ss');
  }
}

async function handleSubmit() {
  await validate();
  const func = isAdd.value ? fetchAddCjProject : fetchUpdateCjProject;
  const { error, data } = await func(model);
  if (!error && data) {
    window.$message?.success(isAdd.value ? $t('common.addSuccess') : $t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  }
}

function closeDrawer() {
  visible.value = false;
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="$t('page.sampling.project.code')" path="code">
          <NInput v-model:value="model.code" :placeholder="$t('page.sampling.project.form.code')" />
        </NFormItem>
        <NFormItem :label="$t('page.sampling.project.name')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.sampling.project.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.sampling.project.projectType')" path="projectType">
          <NSelect
            v-model:value="model.projectType"
            :placeholder="$t('page.sampling.project.form.projectType')"
            :options="dictOptions('cj_project_type')"
          />
        </NFormItem>
        <NFormItem :label="$t('page.sampling.project.projectMode')" path="projectMode">
          <NSelect
            v-model:value="model.projectMode"
            :placeholder="$t('page.sampling.project.form.projectMode')"
            :options="dictOptions('cj_project_mode')"
          />
        </NFormItem>
        <NFormItem :label="$t('page.sampling.project.startDate')" path="startDate">
          <NDatePicker v-model:formatted-value="model.startDate" value-format="yyyy-MM-dd HH:mm:ss" type="date" />
        </NFormItem>
        <NFormItem :label="$t('page.sampling.project.endDate')" path="endDate">
          <NDatePicker v-model:formatted-value="model.endDate" value-format="yyyy-MM-dd HH:mm:ss" type="date" />
        </NFormItem>
        <NFormItem :label="$t('page.sampling.project.description')" path="description">
          <NInput v-model:value="model.description" :placeholder="$t('page.sampling.project.form.description')" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace>
          <NButton quaternary @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
